#!/usr/bin/env python
import random



encyclopedia = []

def searchdat(term):
	print "searching for "+term
	found = []
	for mid in range(len(encyclopedia)):
		meme = encyclopedia[mid]
		print "is "+meme[0]+" "+term+"?"
		if term == meme[0]:
			print "it is!"
			return mid
	print "none of them are!"
	return None

def addmeme(data,mtype="thing",ex=""):
	existing = searchdat(data)
	if existing == None:
		encyclopedia.append([data,mtype,ex])
		return encyclopedia.index([data,mtype,ex])
	else:
		return existing

def getRandomMeme():
	meme = random.choice(encyclopedia)
	return meme[0] + " the "+ meme[1]


linkage = []

def getlid(a,b,exdata):
	for lid in range(len(linkage)):
		link = linkage[lid]
		if a == link[0] and b == link[1] and exdata == link[3]:
			return lid
	return None

def link(a,b,strength=0,exdata=""):
	lid = getlid(a,b,exdata)
	if lid == None:
		linkage.append([a,b,strength,exdata])
		return linkage.index([a,b,strength,exdata])
	else:
		linkage[lid][2]+=strength
	return lid

def linkmemes(a,b,verb=""):
	aid = addmeme(a)
	bid = addmeme(b)
	return link(aid,bid,1,verb)

def findlinks(term):
	mid = searchdat(term)
	found = []
	for link in linkage:
		print str(link[0])+" is "+ encyclopedia[link[0]][0]
		a = encyclopedia[link[0]][0]
		b = encyclopedia[link[1]][0]
		print "is "+term+" "+a+" or "+b+"?"
		if a == term or b == term:
			print "yes!"
			found.append(link)
	return found

def chooselink(links):
	totalstrength = 0
	for link in links:
		totalstrength += link[2]
	chosenlink = random.randint(0,totalstrength)
	currentstrength = 0
	for link in links:
		currentstrength += link[2]
		if chosenlink <= currentstrength:
			return linkage.index(link)
	return linkmemes("I","confus","is")

def saylink(lid):
	if linkage[lid][3] == "":
		return linkage[lid][0] + " connects somehow to "+ linkage[lid][1]
	return encyclopedia[linkage[lid][0]][0] + " "+linkage[lid][3]+" "+ encyclopedia[linkage[lid][1]][0]
		
def saychosenlink(term):
	return saylink(chooselink(findlinks(term)))

def tick():
	pass
def start(daft):
	pass
def say(daft,r,who,w):
	pass
def stop():
	pass
